<template>
  <div class="p-2">
    <!-- 搜索区域 -->
    <transition>
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form :model="queryParams" :inline="true" label-width="100px" @submit.prevent="handleQuery">
            <el-form-item label="片区名称" prop="companyName">
              <el-input
                v-model="queryParams.districtName"
                placeholder="请输入片区名称"
                clearable
                @keyup.enter="handleQuery"
                @keyup.enter.native.prevent
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>

              <el-button type="warning" icon="Plus" @click="handleAdd">新增</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <!-- 列表区域 -->
    <el-card shadow="hover">
      <el-table v-loading="loading" border :data="buildingList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="60" align="center" />
        <!-- <el-table-column label="片区代码" prop="id" align="center" /> -->
        <el-table-column label="片区名称" prop="districtName" align="center" :show-overflow-tooltip="true" />

        <el-table-column label="地址" prop="remark" align="center" />
        <el-table-column label="创建时间" prop="createTime" align="center" />

        <el-table-column label="操作" align="center" width="200" fixed="right">
          <template #default="scope">
            <!-- <el-button type="primary" link icon="View" @click="handleView(scope.row)">详情</el-button> -->
            <el-button type="primary" link icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button type="danger" v-if="roleSetting === 'admin'" link icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>

    <!-- 新增/修改对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-tabs v-model="activeTab" type="border-card">
        <el-tab-pane label="基本信息" name="basic">
          <el-form ref="buildingFormRef" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="片区名称" prop="districtName">
              <el-input v-model="form.districtName" placeholder="请输入片区名称" />
            </el-form-item>

            <el-form-item label="地址" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入地址" />
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 楼层面积编辑对话框 -->
    <el-dialog title="编辑楼层面积" v-model="floorAreaDialog" width="600px" append-to-body>
      <el-form ref="buildingFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="片区名称" prop="buildingName">
          <el-input v-model="form.buildingName" placeholder="请输入楼宇名称" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="saveFloorAreas">保 存</el-button>
          <el-button @click="floorAreaDialog = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="Building">
import { ref, reactive, getCurrentInstance, ComponentInternalInstance, onMounted } from 'vue';
import { listDistrict, addDistrict, updateDistrict, removeDistrict, getBuilding } from '@/api/system/building';
import { BuildingVO, BuildingQuery, BuildingForm, DistrictVO, BuildingPhotoVO, FloorArea } from '@/api/system/building/types';
import BuildingPhotoUpload from '@/components/BuildingPhotoUpload/index.vue';
import { Picture, Edit } from '@element-plus/icons-vue';
import type { FormInstance } from 'element-plus';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_normal_disable'));

const buildingList = ref<any>([]);
const districtList = ref<DistrictVO[]>([]);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref<string[]>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref('');
const open = ref(false);
const roleSetting = ref(localStorage.getItem('username'));

const queryFormRef = ref<FormInstance>();
const buildingFormRef = ref<FormInstance>();

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  districtName: ''
});

const form = ref<any>({ districtName: '', remark: '' });
const activeTab = ref('basic');
const floorAreaDialog = ref(false);
const floorAreaData = ref<FloorArea[]>([]);

const rules = ref({
  districtName: [{ required: true, message: '片区名称不能为空', trigger: 'blur' }],
  buildingCode: [{ required: true, message: '楼宇代码不能为空', trigger: 'blur' }],
  districtId: [{ required: true, message: '请选择所属片区', trigger: 'change' }],
  totalArea: [{ required: true, message: '总面积不能为空', trigger: 'blur' }],
  totalFloors: [{ required: true, message: '总楼层不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
});

/** 查询楼宇列表 */
const getList = async () => {
  loading.value = true;
  try {
    //queryParams.value
    const res = await listDistrict(queryParams.value);
    buildingList.value = res.rows;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

/** 获取片区列表 */
const getDistrictOptions = async () => {
  try {
    // const res = await getDistrictList();
    // districtList.value = res.data || [];
  } catch (error) {
    console.error('获取片区列表失败:', error);
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    districtName: ''
  };

  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: BuildingVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  title.value = '新增楼宇';
  open.value = true;
};

/** 修改按钮操作 */
const handleUpdate = (row: any) => {
  reset();
  // const id = row.id || ids.value[0];
  // getBuilding(id).then((response) => {
  //   form.value = response.data;
  //   title.value = '修改楼宇';
  //   open.value = true;
  // });
  form.value = { ...row };
  console.log('row===', row);
  title.value = '修改楼宇';
  open.value = true;
};

/** 详情按钮操作 */
const handleView = (row: BuildingVO) => {
  // 可以跳转到详情页面或打开详情对话框
  proxy?.$modal.msg('详情功能待实现');
};

/** 删除按钮操作 */
const handleDelete = async (row?: BuildingVO) => {
  const buildingIds = row?.id ? [row.id] : ids.value;
  await proxy?.$modal.confirm(`是否确认删除选中的数据？`);
  // await removeDistrict({ roleIds: buildingIds });
  await removeDistrict(buildingIds);
  proxy?.$modal.msgSuccess('删除成功');
  getList();
};

/** 提交按钮 */
const submitForm = () => {
  buildingFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (form.value.id) {
        await updateDistrict(form.value);
        proxy?.$modal.msgSuccess('修改成功');
      } else {
        await addDistrict(form.value);
        proxy?.$modal.msgSuccess('新增成功');
      }
      open.value = false;
      getList();
    }
  });
};

/** 取消按钮 */
const cancel = () => {
  open.value = false;
  reset();
};

/** 编辑楼层面积 */
const editFloorAreas = () => {
  if (!form.value.totalFloors || form.value.totalFloors <= 0) {
    proxy?.$modal.msgWarning('请先设置总楼层数');
    return;
  }

  // 初始化楼层面积数据
  const totalFloors = form.value.totalFloors;
  floorAreaData.value = [];

  // 如果已有楼层面积数据，使用现有数据
  if (form.value.floorAreas && form.value.floorAreas.length > 0) {
    floorAreaData.value = [...form.value.floorAreas];
  }

  // 确保有totalFloors个楼层的数据
  for (let i = 1; i <= totalFloors; i++) {
    const existingFloor = floorAreaData.value.find((f) => f.floorNumber === i);
    if (!existingFloor) {
      floorAreaData.value.push({
        floorNumber: i,
        area: 0,
        floorName: `第${i}层`
      });
    }
  }

  // 按楼层号排序
  floorAreaData.value.sort((a, b) => a.floorNumber - b.floorNumber);

  // 只保留totalFloors个楼层的数据
  floorAreaData.value = floorAreaData.value.slice(0, totalFloors);

  floorAreaDialog.value = true;
};

/** 保存楼层面积 */
const saveFloorAreas = () => {
  form.value.floorAreas = [...floorAreaData.value];
  floorAreaDialog.value = false;
  proxy?.$modal.msgSuccess('楼层面积保存成功');
};

/** 表单重置 */
const reset = () => {
  form.value = {
    id: undefined,
    buildingName: '',
    buildingCode: '',
    districtId: '',
    totalArea: 0,
    totalFloors: 1,
    address: '',
    status: '0',
    remark: '',
    photos: [],
    floorAreas: []
  };
  activeTab.value = 'basic';
  buildingFormRef.value?.resetFields();
};

/** 处理照片更新 */
const handlePhotosUpdate = (photos: BuildingPhotoVO[]) => {
  form.value.photos = photos;
};

/** 处理照片变化 */
const handlePhotoChange = () => {
  // 照片变化时的处理逻辑
};

onMounted(() => {
  getList();
  getDistrictOptions();
});
</script>

<style scoped>
.text-success {
  color: #67c23a;
}
.text-warning {
  color: #e6a23c;
}

.photo-preview {
  position: relative;
  display: inline-block;
}

.photo-thumb {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  cursor: pointer;
  border: 1px solid #e4e7ed;
}

.photo-count {
  position: absolute;
  top: -8px;
  right: -8px;
  background: #409eff;
  color: white;
  border-radius: 50%;
  width: 18px;
  height: 18px;
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.no-photo {
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  border-radius: 4px;
  color: #909399;
}

.image-error {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  color: #909399;
}
</style>
